import { createRouter, createWebHistory } from 'vue-router';

import HeaderView from '@/views/HeaderView.vue';
import FooterView from '@/views/FooterView.vue';

const routes = [
  // 用来打开主页
  {
    path: '/' ,
    components: {
      'header': HeaderView,
      'default': () => import('@/views/HomeView.vue'),
      'footer': FooterView
    },
    name: 'root',
    meta: {
      title: '主页'
    }
  },
  // 用来打开登录页面
  {
    path: '/login',
    components: {
      'header': HeaderView,
      'default': () => { 
        console.log('resolve async component');
        return import('@/views/LoginView.vue') 
      },
      'footer': FooterView
    },
    name: 'login',
    meta: {
      title: '登录'
    }
  },
  // 用来打开欢迎页面
  {
    path: '/welcome',
    components: {
      'header': HeaderView,
      'default': () => { 
        console.log('resolve async component: WelcomeView');
        return import('@/views/WelcomeView.vue') 
      },
      'footer': FooterView
    },
    name: 'welcome',
    // 路由独享守卫
    beforeEnter: (to,from) => {
      console.log( `welcome route: 从${from.path}到${to.path}`);
      if( !sessionStorage.getItem( 'username' ) ) {
        // 中断原来的导航操作，并返回一个新的路由对象，从而进入新的导航
        return { name: 'login' };
      }
    },
    meta: {
      title: '欢迎'
    }
  },
  // 实现注销操作
  {
    path: '/logout' ,
    // 路由独享守卫
    beforeEnter: (to,from) => {
      console.log( `logout`);
      if( sessionStorage.getItem( 'username' ) ) {
        sessionStorage.removeItem( 'username' );
      }
      // 通过返回一个 路由对象 实现新的导航
      // return { name: 'root' }
      return { path: '/' } 
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 全局前置守卫
router.beforeEach( (to,from) => {
  console.log( `BeforeEach: ${from.path} to ${to.path}` );
});

// 全局解析守卫
router.beforeResolve( (to, from) => {
  console.log( `BeforeResolve: ${from.path} to ${to.path}` );
});

// 全局后置钩子
router.afterEach( (to,from) => {
  console.log( `AfterEach: ${from.path} to ${to.path}` );
  document.title = to.meta.title ;
});


export default router;
